package com.example.administrator.myapplication.heart;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;


import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.administrator.myapplication.R;

import java.util.Calendar;


public class heart_timer_Fragment extends Fragment implements NumberPicker.OnValueChangeListener{
    private Switch heard_switch;
    private boolean isselected=true ;
    private Button timer_started_bt;
    private Button timer_stop_bt;
    private Button timer_reset_bt;
    private ImageView timer_count_pic;
    private ImageView timer_input_pic;
    private TextView timer_input_show;
    private Button heard_timer_finish_bt;
    private Toolbar toolbar;

    /*下面几个变量用来进行计时器的判断状态*/
    private boolean flag1;
    private boolean flag2=true;
    private boolean flag3=false;
    private long beginer;
    private long ender;
    private Button number_sumbit_bt;

    //下面几个是关于输入模式的时分秒
    private TextView heard_timer_hour;
    private TextView heard_timer_minute;
    private TextView heard_timer_second;
    private LinearLayout ll_time_controller;
    private LinearLayout ll_time_input;


    //用来存储输入时.分，秒
    private int num=0;
    //用来进行判断是否为时分秒哪一个调用
    private int number=0;





    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_heart_timer_, container, false);
        init(view);
        toolbar.setTitle("时间测试");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                heart_main_Fragment fragment =new heart_main_Fragment();
                FragmentManager fm =getActivity().getFragmentManager();
                FragmentTransaction ft =fm.beginTransaction();
                //实现fragment 切换效果
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                ft.replace(R.id.fragment_heart,fragment).commit();
            }
        });

        heard_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //当模式为计时模式时
                if (isChecked) {
                    isselected = false;
                    heard_switch.setText("输入模式");
                    timer_count_pic.setVisibility(View.INVISIBLE);
                    timer_input_pic.setVisibility(View.VISIBLE);
                    timer_input_show.setVisibility(View.INVISIBLE);
                    ll_time_input.setVisibility(View.VISIBLE);
                    ll_time_controller.setVisibility(View.INVISIBLE);



                } else {
                    isselected = true;
                    ll_time_controller.setVisibility(View.VISIBLE);
                    heard_switch.setText("计时模式");
                    timer_count_pic.setVisibility(View.VISIBLE);
                    timer_input_pic.setVisibility(View.INVISIBLE);
                    timer_input_show.setVisibility(View.VISIBLE);
                    ll_time_input.setVisibility(View.INVISIBLE);
                }
            }
        });

        timer_started_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag2 = true;
                start();

            }
        });
        timer_stop_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag3 = true;
                flag2 = true;
                pause();
            }
        });
        timer_reset_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!flag3) {
                    flag2 = false;
                    pause();
                } else {
                    timer_input_show.setText("00:00:00");
                }


            }
        });

        heard_timer_hour.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                number=1;

                buildNumpicker();
            }
        });

        heard_timer_minute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                number =2;
                buildNumpicker();
            }
        });


        heard_timer_second.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                number =3;
                buildNumpicker();
            }
        });




        heard_timer_finish_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String timename="" ;
                if(isselected){
                    timename = String.valueOf(timer_input_show.getText());
                }else{
                    timename =String.valueOf(heard_timer_hour.getText())+":"+
                            String.valueOf(heard_timer_minute.getText())+":"+
                            String.valueOf(heard_timer_second.getText());
                }
                Toast.makeText(getActivity(),timename,Toast.LENGTH_SHORT).show();
                changeFragment();

            }
        });




        return view;

    }


    public void changeFragment(){
        heart_main_Fragment HeartMainFrag =new heart_main_Fragment();
        FragmentManager fm =getFragmentManager();
        FragmentTransaction ft=fm.beginTransaction();
        ft.replace(R.id.fragment_heart,HeartMainFrag).commit();
    }



    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        num=newVal;
    }


    /*
    * 初始化函数
    * */
    public void init(View v) {
        heard_switch = (Switch) v.findViewById(R.id.heart_timer_switch);
        timer_started_bt = (Button) v.findViewById(R.id.heard_timer_start);
        timer_stop_bt = (Button) v.findViewById(R.id.heard_timer_stop);
        timer_reset_bt = (Button) v.findViewById(R.id.heard_timer_reset);
        timer_count_pic = (ImageView) v.findViewById(R.id.heard_timer_count_pic);
        timer_input_pic = (ImageView) v.findViewById(R.id.heard_timer_input_pic);
        timer_input_show = (TextView) v.findViewById(R.id.heard_timer_input_show_tv);
        ll_time_input= (LinearLayout) v.findViewById(R.id.ll_time_input);
        ll_time_controller= (LinearLayout) v.findViewById(R.id.ll_time_controller);
        heard_timer_hour=(TextView)v.findViewById(R.id.heard_timer_hour_tv);
        heard_timer_minute=(TextView)v.findViewById(R.id.heard_timer_minute_tv);
        heard_timer_second=(TextView)v.findViewById(R.id.heard_timer_second_tv);
        heard_timer_finish_bt=(Button)v.findViewById(R.id.bt_heart_timer_finish);//完成按钮
        toolbar= (Toolbar) getActivity().findViewById(R.id.heard_main_toolbar);

    }


    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ender = System.currentTimeMillis() - beginer;
            timer_input_show.setText(toTime(ender));

        }
    };

    public void pause() {
        flag1 = false;
    }






    public class MyThread implements Runnable {
        public void run() {
            while (flag1) {
                try {
                    Thread.sleep(100);
                    Message message = handler.obtainMessage();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void start() {
        beginer = System.currentTimeMillis();
        flag1 = true;
        new Thread(new MyThread()).start();
    }

    private String toTime(long start) {
        long millisecond = start % 1000;
        millisecond = millisecond * 60 / 1000;
        start /= 1000;
        long minute = start / 60;
        long second = start % 60;
        minute %= 60;
        if (flag2)
            return String.format("%02d:%02d:%02d", minute, second, millisecond);
        else {
            String str = "00:00:00";
            return str;

        }
    }

    public void buildNumpicker() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.activity_numberpicker, null);
        NumberPicker numberPicker = (NumberPicker) view.findViewById(R.id.test_numberpicker);
        if (number == 1) {
            //当选中的是小时的时候
            numberPicker.setMinValue(0);
            numberPicker.setMaxValue(23);
            numberPicker.setWrapSelectorWheel(false);
            numberPicker.setOnValueChangedListener(this);

        } else {
            //当选中的是小时的时候
            numberPicker.setMinValue(00);
            numberPicker.setMaxValue(59);
            numberPicker.setWrapSelectorWheel(false);
            numberPicker.setOnValueChangedListener(this);
        }
        builder.setView(view).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int a) {
                String name = String.valueOf(num);
                if(Integer.parseInt(name)>=0&&Integer.parseInt(name)<=9){
                    name="0"+name;
                }
                switch (number) {
                    case 1:
                        heard_timer_hour.setText(name);
                        break;
                    case 2:
                        heard_timer_minute.setText(name);
                        break;
                    case 3:
                        heard_timer_second.setText(name);
                        break;
                }
            }
        }).show();
    }
}
